# CodeSkulptor runs Python programs in your browser.
# Click the upper left button to run this simple demo.

# CodeSkulptor runs in Chrome 18+, Firefox 11+, and Safari 6+.
# Some features may work in other browsers, but do not expect
# full functionality.  It does NOT run in Internet Explorer.

import simplegui
import math

message = "Click some points to create trajectory"

points=[]


# Handler for mouse click
def printTraj(lpoints,func):
    global message
    message = "See console!"
    p0=None
    p00=None
    for p in lpoints:
        alpha=0
        if p00!=None:
            alphaPrev=math.atan2(p0[0]-p00[0],p0[1]-p00[1])/math.pi*180
            alphaNext=math.atan2(p[0]-p0[0],p[1]-p0[1])/math.pi*180
            alpha = int(alphaNext - alphaPrev)
            if alpha>180:
               alpha = alpha-360
            if alpha<-180:
               alpha = alpha+360
        if p0!=None:
            len = int(math.sqrt((p0[0]-p[0])**2+(p0[1]-p[1])**2))
            print func+"(",alpha,",",len,");"
        p00=p0
        p0=p

def printTrajectory():
    ps = list(points)
    printTraj(ps,"traj_fwd");
    ps.reverse()
    printTraj(ps,"traj_bak");
    

# Handler to draw on canvas
def draw(canvas):
    canvas.draw_text(message, [50,112], 48, "Red")
    p0=None
    for p in points:
        canvas.draw_circle(p, 4, 1, 'white')
        if p0!=None:
            canvas.draw_line(p0, p, 2, 'Red')
        p0=p
    
def mouse_handler(position):
    points.append(position)
   


# Create a frame and assign callbacks to event handlers
frame = simplegui.create_frame("Home", 800, 600)
frame.add_button("Print trajectory", printTrajectory)
frame.set_draw_handler(draw)
frame.set_mouseclick_handler(mouse_handler)    

# Start the frame animation
frame.start()

